package com.weibo.api;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weibo.util.HttpKit;

/**
 * 微博授权
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2014-4-15 下午1:38:02
 */
public class WBOauth {

	private String clientId;
	private String clientSecret;
	private String redirectUri;
	
	private static final String AUTH_URL = "https://api.weibo.com/oauth2/authorize";
	private static final String TOKEN_URL = "https://api.weibo.com/oauth2/access_token";

	public static WBOauth build() {
		WBOauth oauth = new WBOauth();
		oauth.setClientId(WeiBo.props.get("app_id"));
		oauth.setClientSecret(WeiBo.props.get("app_secret"));
		oauth.setRedirectUri(WeiBo.props.get("redirect_url"));
		return oauth;
	} 
	
	/**
	 * @throws UnsupportedEncodingException 
	 * 获取授权url
	 * DOC：http://open.weibo.com/wiki/%E7%BD%91%E9%A1%B5%E6%8E%88%E6%9D%83%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E5%9F%BA%E6%9C%AC%E4%BF%A1%E6%81%AF
	 * @param @return	设定文件
	 * @return String	返回类型
	 * @throws
	 */
	public String getAuthorizeUrl(boolean isTouch) throws UnsupportedEncodingException {
		Map<String, String> params = new HashMap<String, String>();
		//client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&scope=snsapi_base
		params.put("response_type", "code");
		params.put("client_id", getClientId());
		params.put("redirect_uri", getRedirectUri());
		params.put("scope", "snsapi_base");
		if (isTouch) {
			params.put("display", "mobile");
		}
		return HttpKit.initParams(AUTH_URL, params);
	}
	
	/**
	 * 根据code，拿取uid
	 * @param @param code
	 * @param @return	设定文件
	 * @return String	返回类型
	 * @throws UnsupportedEncodingException 
	 * @throws
	{ 
		"access_token":"",   //走snsapi_base式的网页授权流程，则access_token字段为空
		"remind_in":3600, 
		"expires_in":3600,
		"uid":"UID",
		"scope":"snsapi_base"
	}
	 */
	public JSONObject getTokenByCode(String code) throws UnsupportedEncodingException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", code);
		params.put("client_id", getClientId());
		params.put("client_secret", getClientSecret());
		params.put("grant_type", "authorization_code");
		params.put("redirect_uri", getRedirectUri());
		String userInfo = HttpKit.post(TOKEN_URL, params);
		JSONObject dataMap = JSON.parseObject(userInfo);
		return dataMap;
	}

	public String getClientId() {
		return clientId;
	}
	public void setClientId(String clientId) {
		this.clientId = clientId;
	}

	public String getClientSecret() {
		return clientSecret;
	}

	public void setClientSecret(String clientSecret) {
		this.clientSecret = clientSecret;
	}

	public String getRedirectUri() {
		return redirectUri;
	}
	public void setRedirectUri(String redirectUri) {
		this.redirectUri = redirectUri;
	}
}
